<template>
	<view class="address-container">
		<!-- 自定义导航栏 - 小程序适配版本 -->
		<view class="custom-navbar" :style="navbarStyle">
			<view class="navbar-content" :style="navbarContentStyle">
				<view class="back-btn" @tap.stop="goBack">
					<u-icon name="arrow-left" size="20" color="#fff"></u-icon>
				</view>
				<view class="navbar-title">
					<text class="title-text">{{ isEdit ? '编辑收货地址' : '添加收货地址' }}</text>
				</view>
			</view>
		</view>
		
		<!-- 表单内容 -->
		<view class="wrapper">
			<view class="form-container">
				<view class="form-item">
					<text class="label">真实姓名:</text>
					<input 
						class="input" 
						v-model="formData.recipient" 
						placeholder="请输入收货人姓名"
						maxlength="20"
					/>
				</view>
				
				<view class="form-item">
					<text class="label">联系方式:</text>
					<input 
						class="input" 
						v-model="formData.phoneNum" 
						placeholder="请输入收货人手机号"
						type="number"
						maxlength="11"
					/>
				</view>
				
				<view class="form-item" @click="showRegionPicker">
					<text class="label">所在地区:</text>
					<input 
						class="input readonly" 
						:value="regionText" 
						placeholder="请选择收货人省市区"
						readonly
					/>
				</view>
				
				<view class="form-item textarea-item">
					<text class="label">详细地址:</text>
					<textarea 
						class="textarea" 
						v-model="formData.addDetail" 
						placeholder="请选择收货人详细地址"
						maxlength="100"
						@input="onTextareaInput"
					/>
					<view class="char-count">{{ charCount }}/100</view>
				</view>
				
				<view class="form-item default-item" @click="toggleDefault">
					<text class="label">设置为默认</text>
					<view class="checkbox" :class="{ checked: formData.isDefault }"></view>
				</view>
			</view>
		</view>
		
		<!-- 底部保存按钮 -->
		<view class="save-btn" @click="saveAddress">
			<text class="save-btn-text">保存</text>
		</view>
		
		<!-- 地区选择器 -->
		<u-picker
			ref="regionPicker"
			:show="showPicker"
			:columns="pickerColumns"
			@confirm="onRegionConfirm"
			@cancel="showPicker = false"
			@close="showPicker = false"
			@change="onColumnChange"
			title="地区选择"
			:loading="pickerLoading"
		></u-picker>
	</view>
</template>

<script>
import api from '@/api/index.js'

export default {
	data() {
		return {
			// 小程序适配相关
			statusBarHeight: 0,
			navBarHeight: 44,
			menuButtonInfo: {
				width: 0,
				height: 0,
				top: 0,
				right: 0,
				bottom: 0,
				left: 0
			},
			windowWidth: 375,
			// 原有数据
			isEdit: false,
			addressId: null,
			formData: {
				recipient: '',
				phoneNum: '',
				addDetail: '',
				isDefault: false
			},
			regionData: [], // 原始地区数据
			pickerColumns: [], // u-picker组件需要的列数据
			showPicker: false,
			areaData: [], // 选中的地区数据
			loading: false,
			pickerLoading: false,
			regionText:''

		}
	},
	
	computed: {
		navbarStyle() {
			return {
				paddingTop: this.statusBarHeight + 'px'
			}
		},
		navbarContentStyle() {
			const paddingRight = (this.menuButtonInfo.width || 0) + (this.menuButtonInfo.right || 0) - this.windowWidth + 10
			return {
				height: this.navBarHeight + 'px',
				paddingRight: paddingRight + 'px'
			}
		},
		buttonStyle() {
			return 'width: 100%; height: 88rpx; border-radius: 44rpx; background: linear-gradient(135deg, #FFB800 0%, #FFA000 100%); border: none;'
		},
		// 字符计数
		charCount() {
			return this.formData.addDetail.length
		}
	},
	
	onLoad(options) {
		this.initMiniProgramAdapt()
		if (options.id) {
			this.isEdit = true
			this.addressId = options.id
			this.loadAddressDetail()
		}
		this.loadRegionData()
	},
	
	methods: {
		// 小程序适配初始化
		initMiniProgramAdapt() {
			// 获取系统信息
			const systemInfo = uni.getSystemInfoSync()
			this.statusBarHeight = systemInfo.statusBarHeight || 0
			this.windowWidth = systemInfo.windowWidth || 375

			// 获取胶囊按钮信息（仅小程序）
			// #ifdef MP
			try {
				this.menuButtonInfo = uni.getMenuButtonBoundingClientRect() || {
					width: 87,
					height: 32,
					top: this.statusBarHeight + 6,
					right: 7,
					bottom: this.statusBarHeight + 38,
					left: this.windowWidth - 94
				}
				this.navBarHeight = this.menuButtonInfo.height + (this.menuButtonInfo.top - this.statusBarHeight) * 2
			} catch (e) {
				console.error('获取胶囊按钮信息失败:', e)
				this.menuButtonInfo = {
					width: 87,
					height: 32,
					top: this.statusBarHeight + 6,
					right: 7,
					bottom: this.statusBarHeight + 38,
					left: this.windowWidth - 94
				}
				this.navBarHeight = 44
			}
			// #endif

			// #ifndef MP
			this.menuButtonInfo = {
				width: 0,
				height: 0,
				top: 0,
				right: 0,
				bottom: 0,
				left: 0
			}
			// #endif
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 加载地址详情
		loadAddressDetail() {
			try {
				// 从全局存储中获取编辑地址数据
				const editAddressData = uni.getStorageSync('editAddressData')
				console.log('=======editAddressData=========',editAddressData)
				if (editAddressData) {
					this.formData = {
						recipient: editAddressData.name || editAddressData.recipient || '',
						phoneNum: editAddressData.telephone || editAddressData.phoneNum || '',
						addDetail: editAddressData.address || editAddressData.addDetail || '',
						isDefault: editAddressData.is_default == 1 || editAddressData.isDefault || false
					}
					// 设置地区数据
					this.areaData = [
						{ 
							id: editAddressData.province_id, 
							value: editAddressData.province || editAddressData.provinceName || ''
						},
						{ 
							id: editAddressData.city_id, 
							value: editAddressData.city || editAddressData.cityName || ''
						},
						{ 
							id: editAddressData.district_id, 
							value: editAddressData.district || editAddressData.districtName || ''
						}
					]
					this.regionText = editAddressData.location
					
					// 设置picker的初始选中位置（在地区数据加载完成后）
					this.$nextTick(() => {
						this.setPickerValue()
					})
				} else {
					console.warn('未找到编辑地址数据')
					uni.showToast({
						title: '数据加载失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('加载地址详情失败:', error)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			}
		},
		
		// 加载地区数据
		async loadRegionData() {
			try {
				const res = await api.addressApi.getAllRegion()
				console.log('地区数据API响应:', res)
				if (res.code === 200 || res.r === 0) {
					this.regionData = res.data.gr || res.data
					console.log('地区数据结构:', this.regionData)
					this.processRegionData()
				} else {
					console.error('地区数据加载失败:', res)
				}
			} catch (error) {
				console.error('加载地区数据失败:', error)
			}
		},
		
		// 处理地区数据为u-picker组件需要的格式
		processRegionData() {
			if (!this.regionData || this.regionData.length === 0) {
				console.log('地区数据为空')
				return
			}
			
			// 省份列
			const provinces = this.regionData.map(province => ({
				text: province.region_name,
				value: province.region_name,
				id: province.id
			}))
			
			// 城市列（默认第一个省份的城市）
			let cities = []
			if (this.regionData[0] && this.regionData[0].child) {
				cities = this.regionData[0].child.map(city => ({
					text: city.region_name,
					value: city.region_name,
					id: city.id
				}))
			}
			
			// 区县列（默认第一个城市的区县）
			let districts = []
			if (this.regionData[0] && this.regionData[0].child[0] && this.regionData[0].child[0].child) {
				districts = this.regionData[0].child[0].child.map(district => ({
					text: district.region_name,
					value: district.region_name,
					id: district.id
				}))
			}
			
			// 设置u-picker需要的columns格式
			this.pickerColumns = [provinces, cities, districts]
			
			console.log('处理后的地区数据:', {
				provinces: provinces.length,
				cities: cities.length,
				districts: districts.length
			})
		},
		
		// 显示地区选择器
		showRegionPicker() {
			this.showPicker = true
		},
		
		// u-picker列变化事件（级联选择）
		onColumnChange(e) {
			console.log('u-picker列变化事件:', e)
			const { columnIndex, index } = e
			
			if (columnIndex === 0) {
				// 省份变化，更新城市列表
				const selectedProvince = this.regionData[index]
				console.log('选中的省份:', selectedProvince?.region_name)
				
				if (selectedProvince && selectedProvince.child) {
					const cities = selectedProvince.child.map(city => ({
						text: city.region_name,
						value: city.region_name,
						id: city.id
					}))
					
					// 更新区县列表（选择第一个城市的区县）
					let districts = []
					if (selectedProvince.child[0] && selectedProvince.child[0].child) {
						districts = selectedProvince.child[0].child.map(district => ({
							text: district.region_name,
							value: district.region_name,
							id: district.id
						}))
					}
					
					console.log('更新城市数据:', cities.length, '更新区县数据:', districts.length)
					
					// 更新pickerColumns数据
					this.pickerColumns = [
						this.pickerColumns[0], // 保持省份数据不变
						cities, // 新的城市数据
						districts // 新的区县数据
					]
				}
			} else if (columnIndex === 1) {
				// 城市变化，更新区县列表
				const currentProvinceIndex = this.$refs.regionPicker?.getIndexs?.()?.[0] || 0
				const selectedProvince = this.regionData[currentProvinceIndex]
				
				console.log('城市变化，当前省份索引:', currentProvinceIndex, '城市索引:', index)
				
				if (selectedProvince && selectedProvince.child) {
					const selectedCity = selectedProvince.child[index]
					if (selectedCity && selectedCity.child) {
						const districts = selectedCity.child.map(district => ({
							text: district.region_name,
							value: district.region_name,
							id: district.id
						}))
						
						console.log('更新区县数据:', districts.length)
						
						// 更新pickerColumns数据
						this.pickerColumns = [
							this.pickerColumns[0], // 保持省份数据不变
							this.pickerColumns[1], // 保持城市数据不变
							districts // 新的区县数据
						]
					}
				}
			}
		},
		
		// u-picker确认选择
		onRegionConfirm(e) {
			console.log('u-picker确认选择:', e)
			const { value, indexs } = e
			
			if (value && value.length >= 3 && indexs && indexs.length >= 3) {
				console.log('选择的值:', value)
				console.log('选择的索引:', indexs)
				
				// 根据选择的文本查找对应的地区数据
				const provinceName = value[0].text || value[0]
				const cityName = value[1].text || value[1]
				const districtName = value[2].text || value[2]
				this.regionText = provinceName + '-' + cityName + '-' + districtName
				
				// 根据索引获取对应的地区ID
				const province = this.regionData[indexs[0]]
				const city = province?.child?.[indexs[1]]
				const district = city?.child?.[indexs[2]]
				
				if (province && city && district) {
					// 正确设置areaData，包含ID信息
					this.areaData = [
						{ id: province.id, value: province.region_name },
						{ id: city.id, value: city.region_name },
						{ id: district.id, value: district.region_name }
					]
					
					console.log('设置的areaData:', this.areaData)
					console.log('计算的regionText:', this.regionText)
				} else {
					console.error('无法获取完整的地区信息')
				}
			} else {
				console.error('选择数据格式不正确:', { value, indexs })
			}
			
			this.showPicker = false
		},
		
		// 设置picker的初始选中位置（编辑模式使用）
		setPickerValue() {
			if (this.areaData.length < 3 || !this.regionData.length) {
				return
			}
			
			// 查找省份索引
			const provinceIndex = this.regionData.findIndex(p => p.id == this.areaData[0].id)
			if (provinceIndex === -1) return
			
			// 查找城市索引
			const selectedProvince = this.regionData[provinceIndex]
			if (!selectedProvince || !selectedProvince.child) return
			
			const cityIndex = selectedProvince.child.findIndex(c => c.id == this.areaData[1].id)
			if (cityIndex === -1) return
			
			// 查找区县索引
			const selectedCity = selectedProvince.child[cityIndex]
			if (!selectedCity || !selectedCity.child) return
			
			const districtIndex = selectedCity.child.findIndex(d => d.id == this.areaData[2].id)
			if (districtIndex === -1) return
			
			// 更新picker的列数据以匹配选中的地区
			const provinces = this.regionData.map(province => ({
				text: province.region_name,
				value: province.region_name,
				id: province.id
			}))
			
			const cities = selectedProvince.child.map(city => ({
				text: city.region_name,
				value: city.region_name,
				id: city.id
			}))
			
			const districts = selectedCity.child.map(district => ({
				text: district.region_name,
				value: district.region_name,
				id: district.id
			}))
			
			// 更新picker的列数据
			this.pickerColumns = [provinces, cities, districts]
			
			// 设置picker的默认选中值
			this.$nextTick(() => {
				if (this.$refs.regionPicker && this.$refs.regionPicker.setIndexs) {
					this.$refs.regionPicker.setIndexs([provinceIndex, cityIndex, districtIndex])
				}
			})
		},
		
		// 切换默认地址
		toggleDefault() {
			this.formData.isDefault = !this.formData.isDefault
		},
		
		// 文本域输入事件
		onTextareaInput(e) {
			const value = e.detail.value
			if (value.length > 100) {
				this.formData.addDetail = value.substring(0, 100)
			}
		},
		
		// 验证表单
		validateForm() {
			const reg = /^1[3-9]\d{9}$/
			
			if (!this.formData.recipient.trim()) {
				uni.showToast({
					title: '请填写收货人姓名',
					icon: 'none'
				})
				return false
			}
			
			if (!this.formData.phoneNum.trim()) {
				uni.showToast({
					title: '请填收货人手机号码',
					icon: 'none'
				})
				return false
			}
			
			if (!reg.test(this.formData.phoneNum.trim())) {
				uni.showToast({
					title: '请正确填写手机号码!',
					icon: 'none'
				})
				return false
			}
			
			if (this.areaData.length < 3) {
				uni.showToast({
					title: '请选择所在地区!',
					icon: 'none'
				})
				return false
			}
			
			if (!this.formData.addDetail.trim()) {
				uni.showToast({
					title: '请填写详细地址!',
					icon: 'none'
				})
				return false
			}
			
			return true
		},
		
		// 保存地址
		async saveAddress() {
			if (!this.validateForm()) {
				return
			}
			
			try {
				this.loading = true
				
				const requestData = {
					name: this.formData.recipient,
					telephone: this.formData.phoneNum,
					province_id: this.areaData[0].id,
					city_id: this.areaData[1].id,
					district_id: this.areaData[2].id,
					location: this.regionText,
					address: this.formData.addDetail,
					is_default: this.formData.isDefault ? 1 : 0
				}
				
				let res
				if (this.isEdit) {
					res = await api.addressApi.updateAddress(this.addressId, requestData)
				} else {
					res = await api.addressApi.addAddress(requestData)
				}
				
				if (res.r === 0) {
					uni.showToast({
						title: res.msg || (this.isEdit ? '修改成功' : '添加成功'),
						icon: 'success'
					})
					uni.setStorageSync('shouldRefreshAddressList', true)
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						title: res.msg || '保存失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('保存地址失败:', error)
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		}
	}
}
</script>

<style lang="scss" scoped>
/* 容器样式 */
.address-container {
	background-color: #f8f8f8;
	height: 100vh;
	overflow: hidden;
	display: flex;
	flex-direction: column;
	padding-bottom: 120rpx;
	box-sizing: border-box;
}

.wrapper {
	padding: 30rpx 20rpx 20rpx;
	flex: 1;
	overflow-y: auto;
	margin-top: 150rpx;
}

/* 导航栏样式 */
.custom-navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 999;
	background: linear-gradient(135deg, #FF8033 0%, #FF6B35 100%);
}

.custom-navbar .navbar-content {
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	position: relative;
}

.custom-navbar .back-btn {
	width: 64rpx;
	height: 64rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
	z-index: 10;
}

.custom-navbar .navbar-title {
	position: absolute;
	left: 0;
	right: 0;
	display: flex;
	align-items: center;
	justify-content: center;
	pointer-events: none;
}

.custom-navbar .navbar-title .title-text {
	font-size: 40rpx;
	font-weight: 600;
	color: #fff;
	letter-spacing: 1rpx;
}


.form-container {
	background-color: #fff;
	border-radius: 16rpx;
	overflow: hidden;
}

.form-item {
	display: flex;
	align-items: flex-start;
	padding: 30rpx 40rpx;
	border-bottom: 1rpx solid #f0f0f0;
	position: relative;
}

.form-item:last-child {
	border-bottom: none;
}

.label {
	font-size: 25rpx;
	color: #4B4B4B;
	width: 160rpx;
	flex-shrink: 0;
	line-height: 1.5;
	margin-top: 8rpx;
}

.input {
	flex: 1;
	font-size: 25rpx;
	color: #333;
	padding: 8rpx 0;
	border: none;
	outline: none;
}

.input::placeholder {
	color: #B6B6B6;
}

.readonly {
	background-color: transparent;
}

/* 文本域相关 */
.textarea-item {
	flex-direction: column;
	align-items: stretch;
}

.textarea-item .label {
	width: auto;
	margin-bottom: 20rpx;
}

.textarea {
	width: 100%;
	min-height: 126rpx;
	font-size: 25rpx;
	color: #333;
	border: none;
	outline: none;
	padding: 0;
	line-height: 1.5;
	resize: none;
}

.textarea::placeholder {
	color: #B6B6B6;
}

.char-count {
	text-align: right;
	color: #e8e8e8;
	font-size: 24rpx;
	margin-top: 10rpx;
}

/* 默认地址设置 */
.default-item {
	justify-content: space-between;
	align-items: center;
}

.default-item .label {
	width: auto;
	margin: 0;
}

.checkbox {
	width: 30rpx;
	height: 30rpx;
	/* background: url('') no-repeat center center; */
	background-size: 100% 100%;
	border: 2rpx solid #111;
	border-radius: 4rpx;
}

.checkbox.checked {
	background-color: #007aff;
	border-color: #007aff;
	background-image: url('');
}

/* 底部保存按钮 */
.save-btn {
	position: fixed;
	bottom: 40rpx;
	left: 30rpx;
	right: 30rpx;
	height: 88rpx;
	background: linear-gradient(135deg, #FFB800 0%, #FFA000 100%);
	border-radius: 44rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	z-index: 999;
}

.save-btn-text {
	color: #fff;
	font-size: 32rpx;
	font-weight: 500;
}

/* 地区选择器弹窗样式 */
.region-popup {
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
}

.popup-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 30rpx 40rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.cancel-btn, .confirm-btn {
	font-size: 28rpx;
	color: #007aff;
}

.title {
	font-size: 32rpx;
	color: #333;
	font-weight: 500;
}

.picker-view {
	height: 400rpx;
	width: 100%;
}

.picker-item {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 80rpx;
	font-size: 28rpx;
	color: #333;
}
</style>